# -* - coding: UTF-8 -* -  
import ConfigParser
import sys
import threading
import time
import os

def print_parse(parser):
    for section in parser.sections():
        print section
        for name, value in parser.items(section):
            print '  %s = %r' % (name, value)

def job1(parser, mutux):
    status = parser.get('test', 'u2')
    i = 0
    if status == "none":
        l = [0, 0, 0, 0, 0, 0]
    else:
        l = [int(k) for k in status.split()]
        for j in l:
            if j == 0:  
               break
            i = i + 1 
    while(1):
        l[i] = 1
        print "job1 " + str(i)
        print l
        mutux.acquire()
        parser.set('test', 'u2', ' '.join([str(k) for k in l]))
        parser.write(open('aa', 'r+'))
        mutux.release()
        if i >= len(l) - 1:
            print "job1 finished"
            break
        time.sleep(4)
        i = i + 1


def job2(parser, mutux):
    status = parser.get('test', 'u3')
    i = 0
    if status == "none":
        l = [0, 0, 0, 0, 0, 0]
    else:
        l = [int(k) for k in status.split()]
        for j in l:
            if j == 0:  
               break
            i = i + 1 

    while(1):
        l[i] = 1 
        print "job2 " + str(i)
        print l
        mutux.acquire()
        parser.set('test', 'u3', ' '.join([str(k) for k in l]))
        parser.write(open('aa', 'r+'))
        mutux.release()
        if i >= len(l) - 1:
            print "job2 finished"
            break
        time.sleep(8)
        i = i + 1

parser_file = "aa"
parser = ConfigParser.SafeConfigParser()
if os.path.exists(parser_file):
    parser.read(parser_file)
    print "exists file"
    print_parse(parser)
else:
    parser.add_section('test')  #添加一个setion
    parser.set('test', 'u1', 'http://localhost:8080')
    parser.set('test', 'u2', 'none')
    parser.set('test', 'u3', '1 0 0 0 1')
    parser.write(open('aa', 'w'))

# mutux = threading.Lock()
# status = {"parser": parser, "lock": mutux}

# th1 = threading.Thread(target = job1, args = (status["parser"], status["lock"]))
# th2 = threading.Thread(target = job2, args = (status["parser"], status["lock"]))
# th1.daemon = True
# th2.daemon = True

# th1.start()
# th2.start()

# while(1):   
#     print_parse(parser)
#     time.sleep(1)
#     if (not th1.is_alive()) and (not th2.is_alive()):
#         print "finished"
#         break